<?php

!define('BASE_PATH', __DIR__ . '/');
date_default_timezone_set('Asia/Shanghai');

use function Swoole\Coroutine\Http\post;
use function Swoole\Coroutine\run;
use Swoole\Coroutine\Http\Server;

array_shift($argv);
$method = array_shift($argv);
switch ($method) {
    case 'start':
        proxy();
        break;
    case 'stop':
        break;

    default:
        print_r($argv);
        break;
}

// ./proxy start 127.0.0.1:9000

function proxy()
{
    $process = new \Swoole\Process(function () {
        cli_set_process_title('LimProxyer');
        run(function () {
            $server = new Server('0.0.0.0', 8008, false);
            $server->handle('/', function ($request, $response) {
                if ($request->server['request_uri'] == '/favicon.ico') {
                    return $response->end();
                }
                $response->header('Server', 'Proxyer');
                $response->header('Access-Control-Allow-Origin', '*');
                $response->header('Access-Control-Allow-Methods', '*');
                $response->header('Access-Control-Allow-Headers', '*');
                switch ($request->server['request_method']) {
                    case 'POST':
                        $data = $request->post ?? json_decode($request->getContent(), true);
                        break;
                    default:
                        return $response->end();
                }
                $url    = 'http://121.62.23.148:8118' . $request->server['request_uri'];
                $result = post($url, $data, ['timeout' => 3], $request->header, $request->cookie)->getBody();
                $response->end($result);
            });
            $server->start();
        });

    });
    $process->start();
}

class LimProxy
{

    public function __construct()
    {
        // code...
    }

}
